<template>
  <div class="farmer-stats-container">
    <!-- 数据卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '20px' }">
          <div class="data-card-content">
            <div class="data-card-value-container">
              <div class="data-card-icon" style="background-color: #409EFF">
                <el-icon><Crop /></el-icon>
              </div>
              <div class="data-card-info">
                <div class="data-card-title">总产量</div>
                <div class="data-card-value">{{ stats.totalYield }} kg</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '20px' }">
          <div class="data-card-content">
            <div class="data-card-value-container">
              <div class="data-card-icon" style="background-color: #67C23A">
                <el-icon><Goods /></el-icon>
              </div>
              <div class="data-card-info">
                <div class="data-card-title">种植品种</div>
                <div class="data-card-value">{{ stats.varietiesCount }} 种</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '20px' }">
          <div class="data-card-content">
            <div class="data-card-value-container">
              <div class="data-card-icon" style="background-color: #E6A23C">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="data-card-info">
                <div class="data-card-title">种植面积</div>
                <div class="data-card-value">{{ stats.plantingArea }} 亩</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '20px' }">
          <div class="data-card-content">
            <div class="data-card-value-container">
              <div class="data-card-icon" style="background-color: #F56C6C">
                <el-icon><Van /></el-icon>
              </div>
              <div class="data-card-info">
                <div class="data-card-title">出货量</div>
                <div class="data-card-value">{{ stats.shipmentVolume }} kg</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表和表格 -->
    <el-row :gutter="20" class="mb-4">
      <!-- 种植作物分布 -->
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" :body-style="{ padding: '20px' }" v-loading="loading.cropChart">
          <template #header>
            <div class="card-header">
              <span>种植作物分布</span>
            </div>
          </template>
          <div ref="cropChartRef" style="height: 350px;"></div>
        </el-card>
      </el-col>
      
      <!-- 月度产量趋势 -->
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" :body-style="{ padding: '20px' }" v-loading="loading.trendChart">
          <template #header>
            <div class="card-header">
              <span>月度产量趋势</span>
            </div>
          </template>
          <div ref="trendChartRef" style="height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <!-- 产品产量排行 -->
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" :body-style="{ padding: '20px' }" v-loading="loading.ranking">
          <template #header>
            <div class="card-header">
              <span>产品产量排行</span>
              <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="quarter">本季度</el-radio-button>
                <el-radio-button label="year">本年</el-radio-button>
                <el-radio-button label="all">全部</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          
          <el-table :data="yieldRanking" style="width: 100%">
            <el-table-column type="index" width="50" />
            <el-table-column prop="name" label="产品名称" />
            <el-table-column prop="value" label="产量" width="150">
              <template #default="scope">
                {{ scope.row.value }} kg
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <!-- 最近种植活动 -->
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" :body-style="{ padding: '20px' }" v-loading="loading.activities">
          <template #header>
            <div class="card-header">
              <span>最近种植活动</span>
            </div>
          </template>
          
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in recentActivities"
              :key="index"
              :timestamp="activity.time"
              :type="activity.type ? activity.type : 'primary'"
            >
              <h4>{{ activity.title }}</h4>
              <p>{{ activity.content }}</p>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { statsAPI, productAPI } from '@/api/api'
import { 
  DataAnalysis, 
  Crop, 
  Goods, 
  Van 
} from '@element-plus/icons-vue'

export default {
  name: 'FarmerStats',
  components: {
    DataAnalysis,
    Crop,
    Goods,
    Van
  },
  setup() {
    // 图表实例引用
    const cropChartRef = ref(null)
    const trendChartRef = ref(null)
    
    // 图表实例
    let cropChart = null
    let trendChart = null
    
    // 统计数据
    const stats = ref({
      totalYield: 0,
      varietiesCount: 0,
      plantingArea: 0,
      shipmentVolume: 0
    })
    
    // 产品排行数据
    const yieldRanking = ref([])
    
    // 时间范围选择
    const timeRange = ref('month')
    
    // 最近活动
    const recentActivities = ref([])
    
    // 加载状态
    const loading = ref({
      stats: false,
      cropChart: false,
      trendChart: false,
      ranking: false,
      activities: false
    })

    // 获取基础统计数据
    const fetchStats = async () => {
      loading.value.stats = true
      try {
        const response = await statsAPI.getFarmerStats()
        if (response.success) {
          stats.value = response.data
        } else {
          console.error('获取统计数据失败:', response.message)
          // 使用默认数据
          stats.value = {
            totalYield: 1560,
            varietiesCount: 5,
            plantingArea: 45,
            shipmentVolume: 980
          }
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
        // 使用默认数据
        stats.value = {
          totalYield: 1560, 
          varietiesCount: 5,
          plantingArea: 45,
          shipmentVolume: 980
        }
      } finally {
        loading.value.stats = false
      }
    }
    
    // 获取作物分布数据并初始化图表
    const fetchCropDistribution = async () => {
      loading.value.cropChart = true
      try {
        const response = await statsAPI.getCropDistribution()
        if (response.success && response.data) {
          initCropChart(response.data)
        } else {
          console.error('获取作物分布数据失败:', response.message)
          // 使用默认数据
          initCropChart([
            { name: '枸杞', value: 60 },
            { name: '中宁枸杞', value: 30 },
            { name: '青海枸杞', value: 10 }
          ])
        }
      } catch (error) {
        console.error('获取作物分布数据失败:', error)
        // 使用默认数据
        initCropChart([
          { name: '枸杞', value: 60 },
          { name: '中宁枸杞', value: 30 },
          { name: '青海枸杞', value: 10 }
        ])
      } finally {
        loading.value.cropChart = false
      }
    }
    
    // 获取月度产量趋势数据并初始化图表
    const fetchYieldTrend = async () => {
      loading.value.trendChart = true
      try {
        const response = await statsAPI.getYieldTrend()
        if (response.success && response.data) {
          initTrendChart(response.data)
        } else {
          console.error('获取产量趋势数据失败:', response.message)
          // 使用默认数据
          initTrendChart({
            months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            values: [120, 132, 101, 134, 90, 230, 210, 180, 200, 190, 220, 110]
          })
        }
      } catch (error) {
        console.error('获取产量趋势数据失败:', error)
        // 使用默认数据
        initTrendChart({
          months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
          values: [120, 132, 101, 134, 90, 230, 210, 180, 200, 190, 220, 110]
        })
      } finally {
        loading.value.trendChart = false
      }
    }
    
    // 获取产品产量排行
    const fetchYieldRanking = async () => {
      loading.value.ranking = true
      try {
        const response = await productAPI.getProductYieldRanking(timeRange.value)
        if (response.success) {
          yieldRanking.value = response.data || []
        } else {
          console.error('获取产品产量排行失败:', response.message)
          // 使用默认数据
          yieldRanking.value = [
            { name: '特级枸杞', value: 520 },
            { name: '有机枸杞', value: 420 },
            { name: '中宁枸杞', value: 380 },
            { name: '黑枸杞', value: 320 },
            { name: '红枸杞', value: 290 }
          ]
        }
      } catch (error) {
        console.error('获取产品产量排行失败:', error)
        // 使用默认数据
        yieldRanking.value = [
          { name: '特级枸杞', value: 520 },
          { name: '有机枸杞', value: 420 },
          { name: '中宁枸杞', value: 380 },
          { name: '黑枸杞', value: 320 },
          { name: '红枸杞', value: 290 }
        ]
      } finally {
        loading.value.ranking = false
      }
    }
    
    // 获取最近活动
    const fetchRecentActivities = async () => {
      loading.value.activities = true
      try {
        const response = await statsAPI.getRecentActivities()
        if (response.success) {
          recentActivities.value = response.data || []
        } else {
          console.error('获取最近活动失败:', response.message)
          // 使用默认数据
          recentActivities.value = [
            { type: 'success', title: '种植记录', content: '完成新批次枸杞种植', time: '2023-04-10' },
            { type: 'primary', title: '施肥记录', content: '有机肥施肥完成', time: '2023-04-08' },
            { type: 'warning', title: '灌溉记录', content: '中宁地块灌溉', time: '2023-04-05' },
            { type: 'info', title: '采收记录', content: '特级枸杞采收完成', time: '2023-04-01' }
          ]
        }
      } catch (error) {
        console.error('获取最近活动失败:', error)
        // 使用默认数据
        recentActivities.value = [
          { type: 'success', title: '种植记录', content: '完成新批次枸杞种植', time: '2023-04-10' },
          { type: 'primary', title: '施肥记录', content: '有机肥施肥完成', time: '2023-04-08' },
          { type: 'warning', title: '灌溉记录', content: '中宁地块灌溉', time: '2023-04-05' },
          { type: 'info', title: '采收记录', content: '特级枸杞采收完成', time: '2023-04-01' }
        ]
      } finally {
        loading.value.activities = false
      }
    }
    
    // 初始化作物分布图表
    const initCropChart = (data) => {
      if (!cropChartRef.value) return
      
      if (!cropChart) {
        cropChart = echarts.init(cropChartRef.value)
      }
      
      const option = {
        title: {
          text: '作物分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: data.map(item => item.name)
        },
        series: [
          {
            name: '作物分布',
            type: 'pie',
            radius: '50%',
            data: data.map(item => ({
              name: item.name,
              value: item.value
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      
      cropChart.setOption(option)
    }
    
    // 初始化产量趋势图表
    const initTrendChart = (data) => {
      if (!trendChartRef.value) return
      
      if (!trendChart) {
        trendChart = echarts.init(trendChartRef.value)
      }
      
      const option = {
        title: {
          text: '月度产量趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: data.months || []
        },
        yAxis: {
          type: 'value',
          name: '产量(kg)'
        },
        series: [
          {
            data: data.values || [],
            type: 'line',
            smooth: true,
            name: '产量',
            areaStyle: {}
          }
        ]
      }
      
      trendChart.setOption(option)
    }
    
    // 时间范围变化处理
    const handleTimeRangeChange = () => {
      fetchYieldRanking()
    }
    
    // 处理窗口大小变化，调整图表大小
    const handleResize = () => {
      if (cropChart) {
        cropChart.resize()
      }
      if (trendChart) {
        trendChart.resize()
      }
    }
    
    // 生命周期钩子
    onMounted(() => {
      fetchStats()
      fetchCropDistribution()
      fetchYieldTrend()
      fetchYieldRanking()
      fetchRecentActivities()
      
      window.addEventListener('resize', handleResize)
    })
    
    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize)
      
      if (cropChart) {
        cropChart.dispose()
        cropChart = null
      }
      
      if (trendChart) {
        trendChart.dispose()
        trendChart = null
      }
    })
    
    return {
      stats,
      cropChartRef,
      trendChartRef,
      yieldRanking,
      timeRange,
      recentActivities,
      loading,
      handleTimeRangeChange
    }
  }
}
</script>

<style scoped>
.farmer-stats-container {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.data-card {
  margin-bottom: 20px;
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 64px;
  height: 64px;
  border-radius: 8px;
  margin-right: 16px;
  color: #fff;
  font-size: 28px;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-card, .ranking-card, .activity-card {
  margin-bottom: 20px;
}

.activity-timeline {
  padding: 10px;
}

.activity-content {
  padding: 0 0 10px 0;
}

.activity-title {
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.activity-desc {
  color: #606266;
}
</style> 